package com.yun.mult;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by lsy
 * on 2020/8/7 18:02.
 * 多线程交替打印1-100，使用notify机制
 */
public class TestPrintNum {


    public static void main2(String[] args) {
//        Number2 number = new Number2();
//        Thread t1 = new Thread(number);
//        Thread t2 = new Thread(number);
//        t1.start();
//        t2.start();
        LockSupport.park();
        LockSupport.unpark(Thread.currentThread());
        System.out.println(1);
    }

    static class Number2 implements Runnable {
        private int i = 0;
        ReentrantLock lock = new ReentrantLock();
        private Condition condition = lock.newCondition();
        private Thread sleepThread = null;
        public void run() {
            while (i <= 100) {
                try {
                    lock.lock();
                    condition.signal();
                    LockSupport.parkNanos(1);
                    System.out.println(Thread.currentThread() + "---" + i++);

                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }


            }

        }
    }


    public static void main(String[] args) {
        Runnable number = new Number();
        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);
        t1.start();
        t2.start();
    }

    static class Number implements Runnable {
        private int i = 0;

        public void run() {
            while (i <= 100) {
                synchronized (this) {
//                    notify();
//
                    System.out.println(Thread.currentThread() + "--???AAAA-" + i++);
                    try {
                        Thread.sleep(30000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

    }
}
